<script setup>
  import PageLayout from '@/components/PageLayout.vue'
  import DynamicTable from '@/components/DynamicTable.vue'
  import { ElMessage } from 'element-plus'
  import { getUserList, changeUserStatus, resetPassword } from '@/api'
  import { ref, onMounted, useTemplateRef } from 'vue'
  import { ElMessageBox } from 'element-plus'

  // 表单弹窗
  const formRef = useTemplateRef('form')

  // 管理员列表数据
  const userTableData = ref([])

  // 管理员列表表格列
  const userTableColumns = [
    { label: 'Id', prop: 'id' },
    { label: '用户名称', prop: 'username' },
    { label: '真实姓名', prop: 'realName' },
    { label: '性别', prop: 'gender', filter: val => (val === 1 ? '男' : '女') },
    { label: '电话', prop: 'phone' },
    { label: '邮箱', prop: 'email' },
    { label: '创建时间', prop: 'registeredTime' },
    { label: '状态', prop: 'status' },
    { label: '操作', prop: 'options', width: 250 },
  ]

  const handleGetUserList = () => {
    const p = getUserList().then(
      res => (userTableData.value = res.data.users.map(item => ({ ...item, status: item.status == 1 })))
    )

    formRef.value.load(p)
  }

  const onChangeStatus = async row => {
    ElMessageBox.confirm('确认修改用户状态吗？', '提示').then(() => {
      const status = row.status ? 0 : 1
      changeUserStatus({ userId: row.id, status }).then(() => {
        ElMessage.success('用户状态修改成功')
        handleGetUserList()
      })
    })
  }

  const onResetPassword = row => {
    ElMessageBox.confirm('确认重置该用户密码吗？', '提示').then(() => {
      resetPassword({ userId: row.id }).then(() => {
        ElMessage.success('用户密码重置成功')
        handleGetUserList()
      })
    })
  }

  // 刷新管理员列表
  const onFresh = () => {
    handleGetUserList()
  }

  // 页面加载完成后获取管理员列表
  onMounted(() => {
    handleGetUserList()
  })
</script>

<template>
  <page-layout>
    <template #header>
      <el-button @click="onFresh">刷新</el-button>
    </template>

    <dynamic-table :data="userTableData" :columns="userTableColumns" ref="form">
      <template #status="{ row, value }">
        <el-switch
          v-model="row.status"
          inline-prompt
          size="large"
          active-text="启用"
          inactive-text="禁用"
          :beforeChange="() => onChangeStatus(row)"
        />
      </template>
      <template #options="{ row }">
        <el-button type="warning" @click="onResetPassword(row)"> 重置密码 </el-button>
      </template>
    </dynamic-table>
  </page-layout>
</template>
